package io.renren.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class IOUtils {
    public static Map<String, byte[]> getByte(List<Map<String,Object>> list) {
        Map<String, byte[]> stringMap = new HashMap<String, byte[]>();
        byte[] data = new byte[1024];
        ByteArrayOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            for (Map<String,Object> item : list) {
                if(item.get("url")==null){
                    continue;
                }
                inputStream=getInputStreamByUrl((String)item.get("url"));
                outputStream = new ByteArrayOutputStream();
                while (inputStream.read(data) != -1) {
                    outputStream.write(data);
                }
                stringMap.put(item.get("ticket").toString(), outputStream.toByteArray());
            }
            return stringMap;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Referer", "http://www.fii-cc.com");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            org.apache.commons.io.IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {

            }
        }
        return null;
    }

}

